import { FMVCS } from "../../fgui/fmvc/FMVCS";
import Manager from "../../manager/Manager";
import { ConstDefine } from "../common/ConstDefine";
import GameMainView from "./GameMainView";
import GameMainData from "./GameMainData";
import { GlobalEvent } from "../global/Global";
import EventSystem from "../../core/EventSystem";

export default class GameMainCtrl extends FMVCS.FCtrl {
    /** data */
    static data: GameMainData = null;

    constructor() {
        super();
        GameMainCtrl.data = new GameMainData();
    }

    get vo() {
        return GameMainCtrl.data.vo;
    }

    /** 事件监听注册 */
    rigisterEventListener() {
        this.on(GlobalEvent.UIListenID.UI_LevelChoose, this.onLevelChoose, this);
        this.on(GlobalEvent.UIListenID.UI_BtnRestart_Click, this.onRestart, this);
        this.on(GlobalEvent.UIListenID.UI_GameMainView_Close, this.closeView, this);
        this.on(GlobalEvent.GameEventID.GameMapCreate, this.onGameMapCreate, this);
        this.on(GlobalEvent.GameEventID.GameCustomMap, this.onGameCustomMap, this);
        this.on(GlobalEvent.GameEventID.GameMapRivisions, this.onGameMapRivisions, this);
    }

    onLevelChoose(index: number) {
        this.vo.pattern = ConstDefine.GameMain.Pattern.normal;
        this.vo.level = index;
        let curCfg = GameMainCtrl.data.getCurConfig();
        if(curCfg){
            GameMainCtrl.data.setLevelConfig(curCfg);
            this.openView();
        }
    }

    openView() {
        Manager.fui.open(ConstDefine.UI.GameMainView, GameMainView);
    }

    closeView() {
        Manager.fui.close(ConstDefine.UI.GameMainView);
    }

    onRestart(){
        GameMainCtrl.data.reset();
        this.closeView();
        this.openView();
    }

    onGameMapCreate(starCfg: ConstDefine.Config.StarConfig){
        this.vo.pattern = ConstDefine.GameMain.Pattern.create;
        GameMainCtrl.data.setLevelConfig(starCfg);
        this.openView();
    }

    onGameCustomMap(starCfg: ConstDefine.Config.StarConfig){
        this.vo.pattern = ConstDefine.GameMain.Pattern.custom;
        GameMainCtrl.data.setLevelConfig(starCfg);
        this.openView();
    }

    onGameMapRivisions(starCfg: ConstDefine.Config.StarConfig){
        this.vo.pattern = ConstDefine.GameMain.Pattern.rivisions;
        GameMainCtrl.data.setLevelConfig(starCfg);
        this.openView();
    }

    static gameResult(isWin: boolean){
        let level = 0;
        if(this.data.getIsNormal())
            level = this.data.vo.level;
        let resultData: ConstDefine.Result.ResultEventData = {
            isWin: isWin,
            level: level,
            map: this.data.curConfig,
            pattern: this.data.vo.pattern
        }
        EventSystem.emit(GlobalEvent.GameEventID.GameResult, resultData);
    }
}
